<template>
  <div class="verification-record-list">
    <!-- 搜索表单 -->
    <search-form
      v-model="searchForm"
      :loading="loading"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="任务名称">
        <el-input v-model="name" placeholder="请输入任务名称" clearable/>
      </el-form-item>

      <el-form-item label="漏洞名称">
        <el-input v-model="vuln_title" placeholder="请输入漏洞名称" clearable/>
      </el-form-item>
      <el-form-item label="时间范围" >
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
    </search-form>
    <div class="page-actions" style="margin: 10px 0;">
        <el-button
          icon="Download"
          @click="handleExportResult"
          :disabled="!selectedRows.length"
          plain
          type="primary"
          >导出报告</el-button
        >
      </div>
    <!-- 漏洞列表 -->
    <base-table
      :data="tableData"
      :loading="loading"
      :total="total"
      v-model:page="page"
      v-model:limit="limit"
      @pagination="handlePagination"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="env_id" label="环境ID" width="80"/>
      <el-table-column prop="name" label="任务名称" >
         <template #default="{ row }">
       <el-tooltip :content="row.name" placement="top" :show-after="1000">
        <span class="ellipsis">{{ row.name }}</span>
        </el-tooltip>
      </template>
      </el-table-column>
      <el-table-column prop="vuln_title" label="漏洞名称" width="340"/>
      <el-table-column prop="env_type_info" label="环境类型" width="100"/>
      <el-table-column prop="create_time" label="创建时间" width="170">
        <template #default="{ row }">
          {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link icon="View" @click="handleOpen(row)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </base-table>

    <!-- 信息环境表格弹框 -->
     <el-dialog 
        v-model="open" 
        :title="selected?.name+'-日志记录'" 
        width="1400" 
        :modal="false" 
        :close-on-click-modal="true"
      >
       <log-dialog :ID="selected.id" v-if="open"></log-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import SearchForm from "@/components/SearchForm/index.vue";
import BaseTable from "@/components/BaseTable/index.vue";
import logDialog from "./components/logDialog.vue";
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { getVulnPocList } from "@/api/vulnerability";
import { getVulnFileMatchDetail } from "@/api/vulnMatch.js";
import { downloadFileFromResponse } from "@/utils/fileOpt.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import dayjs from "dayjs";

const loading = ref(false);
const tableData = ref([]);
const page = ref(1);
const limit = ref(10);
const total = ref(0);
const dateRange = ref([]);
const name = ref('');
const vuln_title = ref('');
const router = useRouter();
const searchForm = reactive({});
const selectedRows = ref([]);
const timerId = ref(null);

// 导出结果
const handleExportResult = async () => {
  try {
    if (!selectedRows.value.length) {
      ElMessage.warning("没有可导出的数据");
      return;
    }

    const data = {
      id_list: selectedRows.value,
    };
    const res = await getVulnFileMatchDetail(data);

    // 下载文件
    downloadFileFromResponse(res);

    ElMessage.success("匹配结果导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("匹配结果导出失败");
  }
};

onMounted(() => {
  fetchData();
  timerId.value = setInterval(fetchData, 10000);
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
    timerId.value = null;
  }
});
const fetchData = async () => {
  loading.value = true;
  try {
    let params;
    if(dateRange.value && dateRange.value.length){
      params = {
        page_index: page.value,
        page_size: limit.value,
        name: name.value,
        start_time: dateRange.value[0] ? dayjs(dateRange.value[0]).format('YYYY-MM-DD') : '',
        end_time: dateRange.value[1] ? dayjs(dateRange.value[1]).format('YYYY-MM-DD') : '',
        vuln_title: vuln_title.value,
      }
    } else {
      params = {
        page_index: page.value,
        page_size: limit.value,
        name: name.value,
        vuln_title: vuln_title.value,
      }
    }
    const res = await getVulnPocList(params);
    if(res.code === 200){
      total.value = res.total_items;
      tableData.value = res.data;
    }
  } catch (error) {
    console.error('获取验证记录失败', error);
    ElMessage.error('获取验证记录列表失败');
  } finally {
    loading.value = false;
  }
};

// 详情
const selected = ref();
const open = ref(false);
const handleOpen = async(row)=>{
  selected.value = row;
  open.value = true;
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  dateRange.value = val;
};

// 处理搜索
const handleSearch = () => {
  page.value = 1;
  fetchData();
};

// 处理重置
const handleReset = () => {
  dateRange.value = [];
  name.value = '';
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};
// 处理分页
const handlePagination = () => {
  fetchData();
};

// 处理选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection.map(item => item.id);
};
</script>

<style lang="scss" scoped>
.verification-record-list {
  padding: 16px;

  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      font-size: 20px;
      font-weight: bold;
      margin: 0;
    }
  }

  // 状态徽章样式
  .status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
    font-size: 13px;
    min-width: 90px;
    font-weight: 500;

    .status-indicator {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      display: inline-block;
    }

    &.status-success {
      background-color: rgba(19, 206, 102, 0.15);
      color: #13ce66;

      .status-indicator {
        background-color: #13ce66;
        box-shadow: 0 0 0 2px rgba(19, 206, 102, 0.2);
      }
    }

    &.status-failed {
      background-color: rgba(245, 108, 108, 0.15);
      color: #f56c6c;

      .status-indicator {
        background-color: #f56c6c;
        box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
      }
    }

    &.status-running {
      background-color: rgba(24, 144, 255, 0.15);
      color: #1890ff;

      .status-indicator {
        background-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }

    &.status-waiting {
      background-color: rgba(230, 162, 60, 0.15);
      color: #e6a23c;

      .status-indicator {
        background-color: #e6a23c;
        box-shadow: 0 0 0 2px rgba(230, 162, 60, 0.2);
      }
    }

    &.status-default {
      background-color: rgba(144, 147, 153, 0.15);
      color: #909399;

      .status-indicator {
        background-color: #909399;
        box-shadow: 0 0 0 2px rgba(144, 147, 153, 0.2);
      }
    }
  }

  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);
  }

  :deep(.el-pagination) {
    margin-top: 20px;
    justify-content: flex-end;
  }
}

// 暗色主题适配
html.dark {
  .verification-record-list {
    .status-badge {
      &.status-success {
        background-color: rgba(19, 206, 102, 0.15);
        color: #13ce66;
      }

      &.status-failed {
        background-color: rgba(245, 108, 108, 0.15);
        color: #f56c6c;
      }

      &.status-running {
        background-color: rgba(24, 144, 255, 0.15);
        color: #1890ff;
      }

      &.status-waiting {
        background-color: rgba(230, 162, 60, 0.15);
        color: #e6a23c;
      }

      &.status-default {
        background-color: rgba(144, 147, 153, 0.15);
        color: #909399;
      }
    }
  }
}
</style>
